#include <QDateTimeEdit>
#include "date-time-edit-delegate.h"

DateTimeEditDelegate::DateTimeEditDelegate(QObject *parent) :
    QStyledItemDelegate(parent), m_displayFormat("yyyy.MM.dd h:mm:ss"), m_currentDateTimeAsDefault(true)
{
}

QWidget* DateTimeEditDelegate::createEditor (QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    Q_UNUSED(option);
    Q_UNUSED(index);
    QDateTimeEdit* dateTimeEdit = new QDateTimeEdit(parent);
    dateTimeEdit->setCalendarPopup(true);
    dateTimeEdit->setDisplayFormat(m_displayFormat);
    if (m_currentDateTimeAsDefault)
        dateTimeEdit->setDateTime(QDateTime::currentDateTime());
    else
        dateTimeEdit->setDateTime(m_defaultDateTime);
    QMetaObject::invokeMethod(const_cast<DateTimeEditDelegate*>(this), "setSelectedSection", Qt::QueuedConnection,
                              Q_ARG(QDateTimeEdit*, dateTimeEdit));
    return dateTimeEdit;
}

void DateTimeEditDelegate::setEditorData (QWidget* editor, const QModelIndex& index) const
{
    QDateTime value = index.data(Qt::UserRole).toDateTime();
    m_oldValue = value;

    QDateTimeEdit* dateTimeEdit = static_cast<QDateTimeEdit*>(editor);
    dateTimeEdit->setDateTime(value);
}

void DateTimeEditDelegate::setModelData (QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const
{
    QDateTimeEdit* dateTimeEdit = static_cast<QDateTimeEdit*>(editor);
    QDateTime newValue = dateTimeEdit->dateTime();
    if (newValue == m_oldValue)
        return;

    model->setData(index, newValue, Qt::UserRole);
}

void DateTimeEditDelegate::setDefaultDateTime(QDateTime dateTime)
{
    m_defaultDateTime = dateTime;
}

void DateTimeEditDelegate::setDisplayFormat(QString format)
{
    m_displayFormat = format;
}

void DateTimeEditDelegate::setCurrentDateTimeAsDefault(bool enabled)
{
    m_currentDateTimeAsDefault = enabled;
}

void DateTimeEditDelegate::setSelectedSection (QDateTimeEdit* dateTimeEdit)
{
    dateTimeEdit->setSelectedSection(QDateTimeEdit::NoSection);
}
